<?php
namespace App\Services\WxMass;

use App\Facades\EasyWechat;
use App\Models\WxMassArticle;
use App\Models\WxMassComment;
use App\Services\WxCommon\WxError;

/**
 * 微信评论服务类
 * @package App\Services
 */
class WxMassCommentService extends \App\Services\WxCommon\WxBase
{
    /**
     * 构造函数
     * @param string $appid
     * @throws \Exception
     */
    public function __construct($appid = '')
    {
        parent::__construct($appid);
    }

    /**
     * 打开文章评论
     * @param $massArtId
     * @return bool
     * @throws \Exception
     */
    public function open($massArtId)
    {
        \DB::beginTransaction();
        try{
            $articleModel = WxMassArticle::where('appid', $this->appid)->findOrFail($massArtId);
            //调用微信接口
            $app = EasyWechat::officialAccount($this->appid);
            $apiRs = $app->comment->open($articleModel->msg_data_id, $articleModel->index_num);
            WxError::checkApiResponse($apiRs);
            //设置为打开评论
            $articleModel->open_comment = 1;
            $articleModel->save();
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 关闭评论
     * @param $massArtId
     * @return bool
     * @throws \Exception
     */
    public function close($massArtId)
    {
        \DB::beginTransaction();
        try{
            $articleModel = WxMassArticle::where('appid', $this->appid)->findOrFail($massArtId);
            //调用微信接口
            $app = EasyWechat::officialAccount($this->appid);
            $apiRs = $app->comment->close($articleModel->msg_data_id, $articleModel->index_num);
            WxError::checkApiResponse($apiRs);
            //设置为打开评论
            $articleModel->open_comment = 0;
            $articleModel->save();
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 拉取所有文章评论
     * @return bool
     */
    public function syncAll()
    {
        //只拉取20天内的评论数据
        $artList = WxMassArticle::where('appid', $this->appid)->where('msg_data_id', '<>', 0)->where('created_at', '>', strtotime('-20 days') )->get();
        $artList && $artList = $artList->toArray();
        if (!empty($artList)){
            //将所有需要拉取评论的文章丢到队列中拉取
            foreach ($artList as $article){
                \App\Jobs\WxMassCommentDownload::dispatch($this->appid, $article['id'])->onQueue('default');
            }
        }
        return true;
    }

    /**
     * 同步指定文章的评论列表
     * @param $massArtId
     * @param bool $isAll
     * @throws \Exception
     */
    public function sync($massArtId, $isAll = false)
    {
        $articleModel = WxMassArticle::where('appid', $this->appid)->findOrFail($massArtId);
        $pageOffset = $isAll ? 0 : $articleModel->sync_comment_position;
        $pageSize = 49;
        $app = EasyWechat::officialAccount($this->appid);
        do{
            //调用微信接口
            $apiRs = $app->comment->list($articleModel->msg_data_id, $articleModel->index_num, $pageOffset, $pageSize);
            WxError::checkApiResponse($apiRs);

            if (!empty($apiRs['comment'])){
                foreach ($apiRs['comment'] as $comment){
                    WxMassComment::updateOrCreate(
                        [
                            'appid' => $this->appid,
                            'user_comment_id' => $comment['user_comment_id'],
                        ],
                        [
                            'mass_id' => $articleModel->mass_id ?? 0,
                            'msg_data_id' => $articleModel->msg_data_id ?? 0,
                            'index_num' => $articleModel->index_num ?? 0,
                            'around_openid' => $comment['aroundopenid'] ??'',
                            'around_content' => $comment['aroundcontent'] ?? '',
                            'around_comment_type' => $comment['aroundcomment_type'] ?? 0,
                            'around_create_time' => $comment['aroundcreate_time'] ?? time(),
                            'reply_content' =>$comment['around_reply']['content'] ?? '',
                            'reply_create_time' => $comment['around_reply']['create_time'] ?? time(),
                        ]
                    );
                }
            }

            $curTotal = $apiRs['total'] ?? 0;
            $pageOffset += $curTotal;
            $articleModel->sync_comment_position = $pageOffset;
            $articleModel->save();
        }while($curTotal != 0 && $curTotal == $pageSize);
    }

    /**
     * 将评论标记精选
     * @param $commentId
     * @return bool
     * @throws \Exception
     */
    public function markelect($commentId)
    {
        \DB::beginTransaction();
        try{
            $commentModel = WxMassComment::where('appid', $this->appid)->findOrFail($commentId);
            //调用微信接口
            $app = EasyWechat::officialAccount($this->appid);
            $apiRs = $app->comment->markElect($commentModel->msg_data_id, $commentModel->index_num, $commentModel->user_comment_id);
            WxError::checkApiResponse($apiRs);
            //设置为精选评论
            $commentModel->around_comment_type = 1;
            $commentModel->save();
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 将评论取消精选
     * @param $commentId
     * @return bool
     * @throws \Exception
     */
    public function unmarkelect($commentId)
    {
        \DB::beginTransaction();
        try{
            $commentModel = WxMassComment::where('appid', $this->appid)->findOrFail($commentId);
            //调用微信接口
            $app = EasyWechat::officialAccount($this->appid);
            $apiRs = $app->comment->unmarkElect($commentModel->msg_data_id, $commentModel->index_num, $commentModel->user_comment_id);
            WxError::checkApiResponse($apiRs);
            //取消精选评论
            $commentModel->around_comment_type = 0;
            $commentModel->save();
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 留言删除
     * @param $commentId
     * @return bool
     * @throws \Exception
     */
    public function delete($commentId)
    {
        \DB::beginTransaction();
        try{
            $commentModel = WxMassComment::where('appid', $this->appid)->findOrFail($commentId);
            //调用微信接口
            $app = EasyWechat::officialAccount($this->appid);
            $apiRs = $app->comment->delete($commentModel->msg_data_id, $commentModel->index_num, $commentModel->user_comment_id);
            WxError::checkApiResponse($apiRs);
            //设置为打开评论
            $commentModel->delete();
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 留言回复
     * @param $commentId
     * @param $replyContent
     * @return bool
     * @throws \Exception
     */
    public function reply($commentId, $replyContent)
    {
        if (empty($replyContent)){
            throw new \Exception('回复内容不能为空');
        }
        \DB::beginTransaction();
        try{
            $commentModel = WxMassComment::where('appid', $this->appid)->findOrFail($commentId);
            //调用微信接口
            $app = EasyWechat::officialAccount($this->appid);
            $apiRs = $app->comment->reply($commentModel->msg_data_id, $commentModel->index_num, $commentModel->user_comment_id, $replyContent);
            WxError::checkApiResponse($apiRs);
            //取消精选评论
            $commentModel->reply_content = $replyContent;
            $commentModel->reply_create_time = time();
            $commentModel->save();
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 留言回复删除
     * @param $commentId
     * @return bool
     * @throws \Exception
     */
    public function replyDelete($commentId)
    {
        \DB::beginTransaction();
        try{
            $commentModel = WxMassComment::where('appid', $this->appid)->findOrFail($commentId);
            //调用微信接口
            $app = EasyWechat::officialAccount($this->appid);
            $apiRs = $app->comment->deleteReply($commentModel->msg_data_id, $commentModel->index_num, $commentModel->user_comment_id);
            WxError::checkApiResponse($apiRs);
            //取消精选评论
            $commentModel->reply_content = '';
            $commentModel->reply_create_time = null;
            $commentModel->save();
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }
}